//
//  CGAddRemindViewController.m
//  SchoolClient
//
//  Created by mac on 15/11/13.
//  Copyright © 2015年 mac. All rights reserved.

#import "CGAddRemindViewController.h"

@interface CGAddRemindViewController ()<UITextViewDelegate>

@property(nonatomic,strong)UIDatePicker *myDatePicker;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UITextField *titleText;
@property(nonatomic,strong)UITextView *contentText;
@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation CGAddRemindViewController

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加新提醒";
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    
    [self layoutUI];
    
}

-(void)layoutUI{
    
    
    self.myDatePicker = [[UIDatePicker alloc]init];
    self.myDatePicker.frame = CGRectMake(0, -10, SCREEN_WIDTH, 216);
    [self.view addSubview:self.myDatePicker];
    self.myDatePicker.minimumDate = [NSDate date];
    [self.myDatePicker addTarget:self action:@selector(dateChange) forControlEvents:UIControlEventValueChanged];
    //时间Title
    CGRect aFrame = CGRectMake(0, 196, 60, 44);
    UILabel *label1 = [[UILabel alloc]initWithFrame:aFrame];
    label1.text = @"  时间:";
    label1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label1];
    //选择的时间
    aFrame.origin.x += 60;
    aFrame.size.width = SCREEN_WIDTH - 60;
    self.timeLabel = [[UILabel alloc]initWithFrame:aFrame];
    self.timeLabel.backgroundColor = [UIColor whiteColor];
    self.timeLabel.textColor = [UIColor blueColor];
    self.timeLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.timeLabel];
    
    //标题Title
    aFrame = label1.frame;
    aFrame.origin.y = CGRectGetMaxY(label1.frame) + 1;
    UILabel *label2 = [[UILabel alloc]initWithFrame:aFrame];
    label2.text = @"  标题:";
    label2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label2];
     //标题内容TextField
    aFrame = self.timeLabel.frame;
    aFrame.origin.y = CGRectGetMaxY(self.timeLabel.frame) + 1;
    self.titleText = [[UITextField alloc]initWithFrame:aFrame];
    //self.titleText.placeholder = @"请输入提醒标题";
    self.titleText.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.titleText.backgroundColor = [UIColor whiteColor];
    self.titleText.textColor = [UIColor blueColor];
    self.titleText.font = [UIFont systemFontOfSize:15];
    self.titleText.text = self.remindTitle;
    [self.view addSubview:self.titleText];
    [self.titleText addTarget:self action:@selector(quitKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    
    
    //内容Title
    aFrame = label2.frame;
    aFrame.origin.y = CGRectGetMaxY(label2.frame) + 1;
    UILabel *label3 = [[UILabel alloc]initWithFrame:aFrame];
    label3.text = @"  内容:";
    label3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label3];
    

    
    //提醒内容TextField
    aFrame = self.titleText.frame;
    aFrame.origin.y = CGRectGetMaxY(self.titleText.frame) + 1;
    aFrame.size.height = SCREEN_HEIGHT - 64 - aFrame.origin.y - 50;
    self.contentText = [[UITextView alloc]initWithFrame:aFrame];
    //self.contentText.placeholder = @"请输入提醒内容";
    //self.contentText.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.contentText.backgroundColor = [UIColor whiteColor];
    self.contentText.textColor = [UIColor blueColor];
    self.contentText.font = [UIFont systemFontOfSize:15];
    self.contentText.delegate = self;
    [self.view addSubview:self.contentText];

    //底部添加一个空白View
    CGRect bFrame = label3.frame;
    bFrame.origin.x = 0;
    bFrame.origin.y += 44;
    bFrame.size.width = 60;
    bFrame.size.height =  self.contentText.frame.size.height - 44;
    UIView *fillView = [[UIView alloc]initWithFrame:bFrame];
    fillView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:fillView];
    
    
    
    //提交Button
    aFrame.origin.x = 20;
    aFrame.origin.y = SCREEN_HEIGHT - 64 - 44;
    aFrame.size.height = 44;
    aFrame.size.width = SCREEN_WIDTH - 40;
    UIButton *submitButton = [[UIButton alloc]initWithFrame:aFrame];
    [submitButton setBackgroundImage:[UIImage imageNamed:@"login_btn_bg"] forState:UIControlStateNormal];
    [submitButton setTitle:@"添加" forState:UIControlStateNormal];
    [self.view addSubview:submitButton];
    [submitButton addTarget:self action:@selector(addNewRemind) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)dateChange{
    
    NSDate *date = self.myDatePicker.date;
    //创建日期模板对象,设置模板的显示格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    //dateFormatter.dateFormat = @"yyyy年MM月dd日  HH时mm分";
    //自动转换成当地时间
    NSString *result = [dateFormatter stringFromDate:date];
    self.timeLabel.text = [NSString stringWithFormat:@"%@",result];
    
    
}

#pragma mark 添加新提醒事件
-(void)addNewRemind{
    //有效性验证
    NSString *content = [self.contentText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *title = [self.titleText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (self.timeLabel.text.length == 0) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请选择提醒时间"];
        return;
    }else if (title.length == 0) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入提醒标题"];
        return;
    }else if (content.length == 0) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入提醒内容"];
        return;
    }
    
    
    //把新消息转成NSdata添加到self.dataArray数组里
    
    CGNotice *notice = [[CGNotice alloc]initWithTitle:title andTime:self.timeLabel.text andContent:content andDate:self.myDatePicker.date andCompany_id:self.company_id andSchool_id:self.school_id];

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notice];
    CGAccountDefault *user = [CGAccountDefault shareAccount];
    self.dataArray = [NSMutableArray arrayWithArray:user.notices];
    [self.dataArray addObject:data];
    //把所有的信息提取出来
    NSMutableArray *sortedArr = [NSMutableArray array];
    for (NSData *myData in self.dataArray) {
        CGNotice *myNotice = [NSKeyedUnarchiver unarchiveObjectWithData:myData];
        [sortedArr addObject:myNotice];
    }
    
    //对日期进行排序
    NSArray *myArray = [sortedArr sortedArrayUsingFunction:dateSort context:nil];
    
    //把所有的信息转成NSdata对象
    [self.dataArray removeAllObjects];
    for (CGNotice *myNotice in myArray) {
        NSData *sortData = [NSKeyedArchiver archivedDataWithRootObject:myNotice];
        [self.dataArray addObject:sortData];
    }
    
    NSLog(@"%@",self.dataArray);
    //把所有的NSdata对象保存到沙河
    user.notices = [NSArray arrayWithArray:self.dataArray];
    [user saveToSandBox];
    
    
    //添加提醒
    //1.创建本地通知
    UILocalNotification *localNote = [[UILocalNotification alloc]init];
    localNote.fireDate = self.myDatePicker.date;
    localNote.alertTitle = title;
    localNote.alertBody = content;
    localNote.soundName = UILocalNotificationDefaultSoundName;
    //设置锁屏状态下显示的一个文字,commanm + L 为模拟器锁屏
    localNote.alertAction = @"快速打开";
    //设置userinfo来传递信息
    if (self.company_id.length == 0) {
        self.company_id = @"cancle";
    }
    if (self.school_id.length == 0) {
        self.school_id = @"cancle";
    }
    
    localNote.userInfo = @{@"fireDate":self.timeLabel.text,@"alertBody":content,@"alertTitle":title,@"company":self.company_id,@"school":self.school_id};
    //2.调度通知
    [[UIApplication sharedApplication] scheduleLocalNotification:localNote];
    
    //3.添加完之后跳转到上一级目录
    NSLog(@"company:%@",self.company_id);
    NSLog(@"school:%@",self.school_id);
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark 日期排序的方法
NSComparisonResult dateSort(CGNotice *notice1, CGNotice *notice2, void *context) {
    static NSDateFormatter *df;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyy-MM-dd HH:mm"];
    });
    
    NSDate *v1 = [df dateFromString: notice1.time];
    NSDate *v2 = [df dateFromString: notice2.time];
    return [v1 compare:v2];   //升序
    //return [v2 compare:v1]; //降序
}




-(void)quitKeyboard{
    
    [self.titleText resignFirstResponder];
}

#pragma mark uitextView代理回收键盘
-(void)textViewDidBeginEditing:(UITextView *)textView{
    
    //self.placeholderLabel.hidden = YES;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyBoard)];
    
}

- (void)dismissKeyBoard {
    
    [self.contentText resignFirstResponder];
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    
    self.navigationItem.rightBarButtonItem = nil;
    self.view.transform = CGAffineTransformIdentity;
    
}


#pragma mark 注册键盘通知
-(void)viewWillAppear:(BOOL)animated{
    /*
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
     */
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardDidShowNotification object:nil];
    [center addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
}

//键盘弹起时
-(void)openKeyboard:(NSNotification *)notification{
    
    if (IS_IPHONE4) {
        [UIView animateWithDuration:0.5 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, -220);
        }];
        
    }else if (IS_IPHONE5) {
        [UIView animateWithDuration:0.5 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, -180);
        }];
        
    }else if (IS_IPHONE6) {
        [UIView animateWithDuration:0.2 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, -120);
        }];
        
    }
    
}

//键盘收起时
-(void)closeKeyboard:(NSNotification*)notification{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

@end
